<template>
    <div style="padding-left:5px;">
        <el-row>
            <el-col align="left">
                <el-form label-width="100px">
                    <el-form-item label="K：">
                        <el-input-number v-model="formData.k" :min="1" :max="20" :step="1"
                                         @change="changeK"></el-input-number>
                    </el-form-item>
                    <el-form-item label="比例（%）：">
                        <template v-for="(item, index) in formData.ratioList">
                            <el-input :key="'kRatio_' + index" v-model="formData.ratioList[index]"
                                      style="width:80px;"></el-input>
                            <span v-if="index != formData.ratioList.length - 1" :key="'kColon_' + index">：</span>
                        </template>
                    </el-form-item>
                    <el-form-item label="公司信息：">
                        <el-table
                                :data="formData.companyList"
                                style="width: 100%">
                            <el-table-column
                                    type="index"
                                    width="50">
                            </el-table-column>
                            <el-table-column
                                    prop="name"
                                    label="托管公司"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.name"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                    prop="nameUnit"
                                    label="产业单位"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.nameUnit"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                    prop="longitude"
                                    label="经度" width="200">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.longitude"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                    prop="latitude"
                                    label="纬度" width="200">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.latitude"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                    prop="demand"
                                    label="需求" width="200">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.demand"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100">
                                <template slot-scope="scope">
                                    <el-button style="margin-left:20px;" icon="el-icon-delete"
                                               @click="delCompany(scope.$index)"></el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-row>
                            <el-col align="center">
                                <el-button type="primary" @click="addCompany">添加</el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <el-form-item label="分包数量：">
                        <el-input-number v-model="formData.packageNum" :min="1" :max="20" :step="1"
                                         @change="changePackageNum"></el-input-number>
                    </el-form-item>
                    <el-form-item label="比例（%）：">
                        <template v-for="(item, index) in formData.packageRatioList">
                            <el-input :key="'packageRatio_' + index" v-model="formData.packageRatioList[index]"
                                      style="width:80px;"></el-input>
                            <span v-if="index != formData.packageRatioList.length - 1"
                                  :key="'packageColon_' + index">：</span>
                        </template>
                    </el-form-item>
                    <el-form-item label="">
                        <el-row>
                            <el-col align="center">
                                <el-button type="primary" @click="calc" :loading="loading">计算</el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <el-form-item label="结果：">
                        <div v-loading="loading">
                            <json-viewer v-if="jsonData" :value="jsonData"></json-viewer>
                            <!--                            <pre>{{response}}</pre>-->
                            <el-button v-if="jsonData" class="tag-read"  type="primary" :data-clipboard-text="jsonDataStr" @click="copy" >复制json数据</el-button>
                            <div style="height: 500px;text-align: left;">
                                <v-chart :option="option" :autoresize="true"/>
                            </div>
                            <div>
                                <div v-for="(partition, partitionIndex) in jsonData"
                                     :key="'partition' + partitionIndex">
                                    <h1>{{'第' + partition.partitionName + '分区，比例：' + formatPercent(partition.ratio, 2) + '%'}}</h1>
                                    <h2>公司信息</h2>
                                    <el-table
                                            :data="partition.companyList"
                                            style="width: 100%">
                                        <el-table-column
                                                type="index"
                                                width="50">
                                        </el-table-column>
                                        <el-table-column prop="name" label="托管公司"></el-table-column>
                                        <el-table-column
                                                prop="nameUnit"
                                                label="产业单位"
                                        >
                                        </el-table-column>
                                    </el-table>
                                    <h2>分包信息</h2>
                                    <el-table
                                            :data="partition.packageList"
                                            style="width: 100%">
                                        <el-table-column
                                                type="index"
                                                width="50">
                                        </el-table-column>
                                        <el-table-column prop="name" label="包序号"></el-table-column>
                                        <el-table-column prop="amount" label="amount">
                                            <template slot-scope="scope">
                                                {{formatNumber(scope.row.amount, 2)}}%
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                                prop="ratio"
                                                label="比例" width="200">
                                            <template slot-scope="scope">
                                                {{formatPercent(scope.row.ratio, 2)}}%
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <hr/>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <div style="padding-left:10px;">

        </div>
    </div>

</template>

<script>
    import lodash from 'lodash'
    import axios from "axios";
    import Clipboard from "clipboard";

    export default {
        data() {
            return {
                loading: false,
                response: null,
                formData: {
                    k: 3,
                    ratioList: [],
                    companyList: [],
                    packageNum: 3,
                    packageRatioList: [],
                },
                jsonData: null,
                pointData: [],
                option: null,
                OPTION_TEMPLATE: {
                    tooltip: {
                        trigger: 'item',
                        formatter: function (params) {
                            return params.marker + params.seriesName + '</br>' + params.name + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + params.data[2]
                        }
                    },
                    xAxis: {
                        scale: true,
                    },
                    yAxis: {
                        scale: true,
                    },
                    legend: {
                        data: []
                    },
                    series: []
                },
            };
        },
        methods: {
            copy() {
                let clipboard = new Clipboard('.tag-read')

                clipboard.on('success', e => {
                    console.log('###e:', e);
                    this.$message({
                        showClose: true,
                        message: '复制成功！',
                        type: 'success'
                    })
                    // 释放内存
                    clipboard.destroy()
                })

                clipboard.on('error', e => {
                    console.error('###e:', e);
                    // 不支持复制
                    this.$message({
                        showClose: true,
                        message: '该浏览器不支持自动复制！',
                        type: 'success'
                    })
                    // 释放内存
                    clipboard.destroy()
                })
            },
            formatNumber(num, precision, separator) {
                let parts;
                // 判断是否为数字
                if (!isNaN(parseFloat(num)) && isFinite(num)) {
                    // 把类似 .5, 5. 之类的数据转化成0.5, 5, 为数据精度处理做准, 至于为什么
                    // 不在判断中直接写 if (!isNaN(num = parseFloat(num)) && isFinite(num))
                    // 是因为parseFloat有一个奇怪的精度问题, 比如 parseFloat(12312312.1234567119)
                    // 的值变成了 12312312.123456713
                    num = Number(num);

                    let precisionLength = 2

                    if (String(num).split(".")[1]) {

                        let len = String(num).split(".")[1].length

                        len < precision ? precisionLength = len : precisionLength = precision

                    }

                    // 处理小数点位数
                    num = (typeof precision !== 'undefined' ? num.toFixed(precisionLength) : num).toString();
                    // 分离数字的小数部分和整数部分
                    parts = num.split('.');
                    // 整数部分加[separator]分隔, 借用一个著名的正则表达式
                    parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + (separator || ','));
                    return parts.join('.');
                }
                return NaN;
            },
            formatPercent(num, precision, separator) {
                let parts;
                // 判断是否为数字
                if (!isNaN(parseFloat(num)) && isFinite(num)) {
                    // 把类似 .5, 5. 之类的数据转化成0.5, 5, 为数据精度处理做准, 至于为什么
                    // 不在判断中直接写 if (!isNaN(num = parseFloat(num)) && isFinite(num))
                    // 是因为parseFloat有一个奇怪的精度问题, 比如 parseFloat(12312312.1234567119)
                    // 的值变成了 12312312.123456713
                    num = Number(num) * 100;
                    // 处理小数点位数
                    num = (typeof precision !== 'undefined' ? num.toFixed(precision) : num).toString();
                    // 分离数字的小数部分和整数部分
                    parts = num.split('.');
                    // 整数部分加[separator]分隔, 借用一个著名的正则表达式
                    parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + (separator || ','));

                    return parts.join('.');
                }
                return NaN;
            },
            changeK() {
                let ratioList = []
                for (let i = 0; i < this.formData.k; i++) {
                    ratioList.push(null)
                }
                this.formData.ratioList = ratioList
            },
            changePackageNum() {
                let ratioList = []
                for (let i = 0; i < this.formData.packageNum; i++) {
                    ratioList.push(null)
                }
                this.formData.packageRatioList = ratioList
            },
            addCompany() {
                this.formData.companyList.push({
                    name: null,
                    nameUnit: null,
                    longitude: null,
                    latitude: null,
                    demand: null,
                })
            },
            delCompany(index) {
                this.formData.companyList.splice(index, 1)
            },
            async calc() {
                let jsonData = null
                let pointData = []
                try {
                    this.loading = true
                    let postData = this.formData
                    let response = await axios.post('/process_cluster', postData)
                    this.response = response.data
                    jsonData = this.response.data
                    pointData = this.response.point_dict
                    // console.log('response:', response)
                    this.loading = false
                } catch (e) {
                    this.response = '出错了'
                    this.loading = false
                    jsonData = null
                }
                this.jsonData = jsonData
                this.pointData = pointData
                let option = lodash.cloneDeep(this.OPTION_TEMPLATE)
                for (let name in this.pointData) {
                    option.legend.data.push(name)
                    let points = this.pointData[name]
                    let series = {
                        name: name,
                        symbolSize: 10,
                        data: [],
                        type: 'scatter'
                    }
                    points.forEach(p => {
                        p[2] = this.formData.companyList[p[2] - 1].name + '(' + p[2] + ')'
                        series.data.push(p)
                    })
                    option.series.push(series)
                }

                this.option = option
            },
        },
        computed: {
            jsonDataStr() {
                return JSON.stringify(this.jsonData,null,2)
            }
        },
        mounted() {
            this.changeK()
            this.changePackageNum()

            this.formData.ratioList = [0.1, 0.3, 0.6]
            this.formData.packageRatioList = [0.1, 0.3, 0.6]

            this.formData.companyList.push({
                name: '巫山公司',
                nameUnit: '巫山县神女峰电业有限责任公司',
                longitude: 109.885643,
                latitude: 31.080783,
                demand: 26.3833
            })
            this.formData.companyList.push({
                name: '巫溪公司',
                nameUnit: '巫溪县宏泰电力实业有限责任公司',
                longitude: 109.576452,
                latitude: 31.404587,
                demand: 20.0259
            })
            this.formData.companyList.push({
                name: '秀山公司',
                nameUnit: '秀山恒联电力建设有限公司',
                longitude: 109.014012,
                latitude: 28.453856,
                demand: 10
            })
            this.formData.companyList.push({
                name: '忠县公司',
                nameUnit: '忠县海银送变电工程有限责任公司',
                longitude: 108.044084,
                latitude: 30.305744,
                demand: 75.50646
            })
            this.formData.companyList.push({
                name: '市区公司',
                nameUnit: '重庆安驰电力工程有限公司',
                longitude: 106.575354,
                latitude: 29.558923,
                demand: 6.7646
            })
            this.formData.companyList.push({
                name: '开县公司',
                nameUnit: '重庆百川盛建筑工程有限公司',
                longitude: 108.399888,
                latitude: 31.166383,
                demand: 110.162
            })
            this.formData.companyList.push({
                name: '市北公司',
                nameUnit: '重庆北源电力工程设计有限公司，重庆北洲实业（集团）有限公司',
                longitude: 106.637708,
                latitude: 29.723857,
                demand: 7.121884
            })
            this.formData.companyList.push({
                name: '送变电',
                nameUnit: '重庆鼎兴电力工程有限公司',
                longitude: 106.517023,
                latitude: 29.508059,
                demand: 0
            })
            this.formData.companyList.push({
                name: '长寿公司',
                nameUnit: '重庆海鼎勘察设计有限公司',
                longitude: 107.08751,
                latitude: 29.86371,
                demand: 9.066004
            })
            this.formData.companyList.push({
                name: '石柱公司',
                nameUnit: '重庆恒丰电力有限公司',
                longitude: 108.120652,
                latitude: 30.005428,
                demand: 28.400647
            })
            this.formData.companyList.push({
                name: '市南公司',
                nameUnit: '重庆恒旺实业有限公司，重庆市驰骋电力设计有限公司，重庆广汇供电服务有限责任公司市南分公司',
                longitude: 106.54697,
                latitude: 29.408072,
                demand: 26.336282
            })
            this.formData.companyList.push({
                name: '展帆公司',
                nameUnit: '重庆展帆电力工程勘察设计咨询有限公司二郎分公司',
                longitude: 106.517023,
                latitude: 29.508059,
                demand: 0
            })
            this.formData.companyList.push({
                name: '北碚公司',
                nameUnit: '重庆缙能实业（集团）有限公司，重庆广汇供电服务有限责任公司北碚分公司',
                longitude: 106.402277,
                latitude: 29.811138,
                demand: 9.8674
            })
            this.formData.companyList.push({
                name: '奉节公司',
                nameUnit: '重庆夔门电力设备安装有限公司',
                longitude: 109.407114,
                latitude: 31.024285,
                demand: 91.917541
            })
            this.formData.companyList.push({
                name: '江津公司',
                nameUnit: '重庆利源巨能实业有限公司',
                longitude: 106.270961,
                latitude: 29.325674,
                demand: 4.5975
            })
            this.formData.companyList.push({
                name: '云阳公司',
                nameUnit: '重庆茂晟电力发展有限公司',
                longitude: 108.703933,
                latitude: 30.936701,
                demand: 242.9451
            })
            this.formData.companyList.push({
                name: '铜梁公司',
                nameUnit: '重庆民能实业有限公司',
                longitude: 106.062515,
                latitude: 29.850968,
                demand: 101.7698
            })
            this.formData.companyList.push({
                name: '黔江公司',
                nameUnit: '重庆市黔江区渝能电气有限责任公司',
                longitude: 108.777471,
                latitude: 29.539286,
                demand: 9.384115
            })
            this.formData.companyList.push({
                name: '合川公司',
                nameUnit: '重庆润德实业有限责任公司',
                longitude: 106.2827,
                latitude: 29.97782,
                demand: 102.0864
            })
            this.formData.companyList.push({
                name: '城口公司',
                nameUnit: '重庆圣伟电力安装有限公司',
                longitude: 108.670789,
                latitude: 31.95324,
                demand: 86.1535
            })
            this.formData.companyList.push({
                name: '大足公司',
                nameUnit: '重庆市大足区精诚电力发展有限责任公司',
                longitude: 105.728134,
                latitude: 29.713391,
                demand: 121.5445
            })
            this.formData.companyList.push({
                name: '潼南公司',
                nameUnit: '重庆市涪江水利水电工程有限责任公司',
                longitude: 105.846823,
                latitude: 30.197571,
                demand: 23.5774
            })
            this.formData.companyList.push({
                name: '涪陵公司',
                nameUnit: '重庆市涪陵区瑞安电力建设工程有限公司',
                longitude: 107.253072,
                latitude: 29.758239,
                demand: 49.231801
            })
            this.formData.companyList.push({
                name: '南川公司',
                nameUnit: '重庆市恒光电力有限责任公司',
                longitude: 107.105718,
                latitude: 29.163561,
                demand: 36.082031
            })
            this.formData.companyList.push({
                name: '江津区公司',
                nameUnit: '重庆市江津区远能电力工程有限公司',
                longitude: 106.270961,
                latitude: 29.325674,
                demand: 4.3708
            })
            this.formData.companyList.push({
                name: ' 垫江公司',
                nameUnit: '重庆市腾泰电力有限责任公司',
                longitude: 107.339146,
                latitude: 30.333286,
                demand: 46.021452
            })
            this.formData.companyList.push({
                name: '万州公司',
                nameUnit: '重庆市万州长江电力实业发展有限公司，重庆广汇供电服务有限责任公司万州分公司',
                longitude: 108.415519,
                latitude: 30.812595,
                demand: 80.7203
            })
            this.formData.companyList.push({
                name: '武隆公司',
                nameUnit: '重庆市武隆区博能电力有限公司',
                longitude: 107.766355,
                latitude: 29.331757,
                demand: 107.900626
            })
            this.formData.companyList.push({
                name: '酉阳公司',
                nameUnit: '重庆市酉阳县光达电气有限责任公司',
                longitude: 108.774413,
                latitude: 28.846998,
                demand: 15.383854
            })
            this.formData.companyList.push({
                name: '璧山公司',
                nameUnit: '重庆市西源电力安装工程有限公司，重庆市新纪元电力勘察设计有限公司，重庆广汇供电服务有限责任公司璧山分公司',
                longitude: 106.211598,
                latitude: 29.583688,
                demand: 10.6777
            })
            this.formData.companyList.push({
                name: '彭水公司',
                nameUnit: '重庆市中安电力开发有限责任公司',
                longitude: 108.172227,
                latitude: 29.299567,
                demand: 73.409855
            })
            this.formData.companyList.push({
                name: '丰都公司',
                nameUnit: '重庆硕源电力实业有限公司',
                longitude: 107.737421,
                latitude: 29.869522,
                demand: 53.719227
            })
            this.formData.companyList.push({
                name: '永川公司',
                nameUnit: '重庆永能实业（集团）有限公司',
                longitude: 105.933253,
                latitude: 29.362501,
                demand: 0
            })
            this.formData.companyList.push({
                name: '綦南公司',
                nameUnit: '重庆元方实业（集团）有限公司，重庆广汇供电服务有限责任公司綦南分公司',
                longitude: 106.65782,
                latitude: 29.03375,
                demand: 81.289541
            })
            this.formData.companyList.push({
                name: '嘉汇公司',
                nameUnit: '重庆展帆电力工程勘察设计咨询有限公司，重庆嘉汇投资有限责任公司',
                longitude: 106.637708,
                latitude: 29.723857,
                demand: 0
            })
        }
    };
</script>
